﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;
using Light.Utility;
using Light.Framework.Castle;
using Light.Framework.Contract;

namespace WxPayAPI
{
    public class PagePayResult<T, ITComponent> : Page
        where ITComponent : IOrderComponent
        where T : class, IOrder, new()
    {
        protected bool IsSuccess = false;
        protected int ProductId = 0;
        protected string OrderCode = "";

        protected string From = WebHelper.Request("from");
        protected string ResultMessgae = WebHelper.Request("msg");
        protected string Err_msg = WebHelper.Request("err_msg");
        protected string Err_desc = WebHelper.Request("err_desc");
        /// <summary>
        /// 在支付结果页点击“返回重新支付”跳到的页面
        /// </summary>
        protected string BackUrl = System.Web.Configuration.WebConfigurationManager.AppSettings["BackUrl"];

        protected Dictionary<string, object> DicParameter = new Dictionary<string, object>();

        protected override void OnLoad(EventArgs e)
        { 
            OrderCode = WebHelper.Request("orderCode"); 
            string status = ""; 
            CheckOrder(ref status, ref ResultMessgae);
            IsSuccess = status.ToLower() == "success" ? true : false;

            Err_msg = WebHelper.Request("err_msg");
            Err_desc = WebHelper.Request("err_desc");
            Log.Info(this.GetType().ToString(), "orderCode " + OrderCode + " PayResult.aspx page load");
            IOrderComponent icomponet = (IOrderComponent)ServerApplication.ComponentFactory.Create<ITComponent>();
            IOrder order = icomponet.GetByOrderCode(OrderCode);
            if (IsSuccess)
            {
                order.PayStatus = PayStatus.Succeed;
            }
            else
            {
                order.PayStatus = PayStatus.Failed;
                order.PayMessage = ResultMessgae + "|" + Err_msg + "|" + Err_desc;
            }
            OperateResult result = icomponet.UpdateByOrderCode(order);
            string msg = @"<div class=""weui_msg"">
                            <div class=""weui_icon_area"">
                             " + (IsSuccess ? @"<i class=""weui_icon_success weui_icon_msg""></i>" : @"<i class=""weui_icon_msg weui_icon_warn""></i>")
                            + @"</div>
                            <div class=""weui_text_area"">
                                <h2 class=""weui_msg_title"">支付" + (IsSuccess ? "成功" : "失败") + @"</h2>             
                            </div>
                            <div class=""weui_opr_area"">
                                <p class=""weui_btn_area"">
                                    <a href=""javascript:backOrClose();"" id=""backOrClose"" class=""weui_btn weui_btn_primary"">" + (IsSuccess ? "确定" : "返回重新支付") + @"</a>
                                    
                                </p>
                            </div>
                        </div>";
            Form.InnerHtml = msg;
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", GetJsApiCall());

            base.OnLoad(e);
        }

        string GetJsApiCall()
        {
            DicParameter.Add("From", From);
            DicParameter.Add("OrderCode", OrderCode);
            DicParameter.Add("IsSuccess", IsSuccess);
            DicParameter.Add("ResultMessgae", ResultMessgae);
            DicParameter.Add("Err_msg", Err_msg);
            DicParameter.Add("Err_desc", Err_desc);

            BackUrl = BackUrl + "?" + Parameter();
            string htmlStr = WxPayAPI.Properties.Resources.JsApiPayPage;

            Match matchJs = Regex.Match(htmlStr, "<script\\s*type=\"text/javascript\"\\s*id=\"PayResult\"\\s*>[\\s\\S]*?</script>");
            string str = matchJs.Value;
            str = Regex.Replace(str, "<%[\\s]*=[\\s]*" + "url" + "[\\s]*%>", BackUrl);

            return str;
        }

        string Parameter()
        {
            string parameterStr = "";
            foreach (string key in DicParameter.Keys)
            {
                parameterStr += "&" + key + "=" + DicParameter[key];
            }
            if (!string.IsNullOrEmpty(parameterStr))
            {
                parameterStr = parameterStr.Substring(1);
            }
            return parameterStr;
        }

        void CheckOrder(ref string trade_state, ref string trade_state_desc)
        {
            string out_trade_no = Request.QueryString["orderCode"];
            string result = OrderQuery.Run("", out_trade_no);//调用订单查询业务逻辑 
            Regex rx_trade_state = new Regex(@"<br>trade_state=[a-zA-Z]*?<br>");
            Regex rx1_trade_state_desc = new Regex(@"<br>trade_state_desc=.*?<br>");
            Match match_rx_trade_state = rx_trade_state.Match(result);
            Match match_rx1_trade_state_desc = rx1_trade_state_desc.Match(result);
            string desc = "";
            if (!string.IsNullOrEmpty(match_rx1_trade_state_desc.Value))
            {
                try
                {
                    desc = match_rx1_trade_state_desc.Value.Replace("<br>", "").Split('=')[1];
                }
                catch (Exception ex)
                {
                    desc = "";
                }

            }
            string status = "";
            if (!string.IsNullOrEmpty(match_rx_trade_state.Value))
            {
                try
                {
                    status = match_rx_trade_state.Value.Replace("<br>", "").Split('=')[1];
                }
                catch (Exception ex)
                {
                    status = "";
                }

            }
            trade_state = status;
            trade_state_desc = desc;
            //Response.Write("{\"trade_state\":\"" + status + "\",\"trade_state_desc\":\"" + desc + "\"}");
            //Response.End();   
        }

    }
}
